<template>
  <el-dialog :title="formData.cabinetId?'修改信息':'添加信息'" :visible.sync="visible">
    <el-form :model="formData" :rules="rules" label-width="80px" ref="dataDom">
      <el-form-item label="展示柜编号" prop="number">
        <el-input v-model="formData.number" placeholder="展示柜编号"/>
      </el-form-item>
      <el-form-item label="展示柜尺寸">
      <el-select v-model="value" placeholder="请选择尺寸">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="formData.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">启用</el-radio>
        </el-radio-group>
      </el-form-item>
<!--      <el-form-item label="所属商铺">
        <el-input v-model="formData.shopId" placeholder="所属商铺"/>
      </el-form-item>-->
      <el-form-item label="商铺" prop="shopId">
        <el-select v-model="formData.shopId" clearable filterable  placeholder="请选择商铺">
          <el-option v-for="item in shopList" :key="item.shopId" :label="item.address+'/'+item.shopName" :value="item.shopId"/>
        </el-select>
      </el-form-item>

      <el-form-item label="照片列表">
        <el-upload :action="uploadUrl" :headers="uploadHeader" :list-type="'picture-card'" :before-upload="beforeUpload" :on-success="uploadSuccess" :file-list="imageList" ref="imageListRef">
          <i class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img :src="file.url" alt="" class="el-upload-list__item-thumbnail">
            <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="showImageDetail(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          class="el-upload-list__item-delete"
          @click="removeImage(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="imageListDialogVisible" append-to-body>
          <img :src="imageListDialogImgSrc" alt="" height="100%" width="100%">
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button @click="visible=false">取消</el-button>
        <el-button type="primary" @click="submitInfo">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const initInfo = {
  cabinetId: '',
  number: '',
  size: '',
  status: 1,
  imageUrls: [],
  shopId: '',
  cover: ''
}
export default {
  name: 'CabinetAddOrUpdate',
  data () {
    return {
      disabled: false,
      visible: false,
      shopList: [],
      formData: {
        ...initInfo
      },
      rules: {
        number: [
          { required: true, message: '展示柜编号不能为空', trigger: 'blur' }
        ],
        size: [
          { required: true, message: '展示柜尺寸不能为空', trigger: 'blur' }
        ],
        cover: [
          { required: true, message: '封面不能为空', trigger: 'blur' }
        ],
        shopId: [
          { required: true, message: '所属商铺不能为空', trigger: 'blur' }
        ]
      },
      loading: '',
      uploadUrl: process.env.VUE_APP_BASE_API + '/upload',
      baseImageUrl: process.env.VUE_APP_BASE_API + '/img/',
      uploadHeader: {
        token: ''
      },
      dialogVisible: false,
      dialogImgSrc: '',
      fileList: [],
      imageList: [],
      imageListDialogVisible: false,
      imageListDialogImgSrc: '',
      /* =====  */
      options: [{
        value: '小型',
        label: '小型'
      }, {
        value: '中型',
        label: '中型'
      }, {
        value: '大型',
        label: '大型'
      }],
      value: ''

    }
  },
  methods: {
    init (cabinetId) {
      /* 开启弹窗 */
      this.visible = true
      this.imageList = []
      this.formData = { ...initInfo }

      /* 获取所有的展示柜id */
      this.$http.get('/cabinet/shoplist').then(data => {
        if (data.code === 0) {
          this.shopList = data.list
        }
      })

      /* 判断userId是否有值 */
      if (cabinetId) {
        /* 成立表示该次操作为修改，发送ajax请求获取信息 */
        this.$http.get('/cabinet/info/' + cabinetId).then(data => {
          if (data.code === 0) {
            this.formData = {
              ...data.list
            }
            /* 处理多张图片数据 */
            if (this.imageList.length > 0) {
              this.imageList.length = 0
            }
            this.imageList = this.formData.imageList.map(item => {
              return {
                name: item.imageUrl,
                url: this.baseImageUrl + item.imageUrl
              }
            })
            /* 处理提交的表单中的imageUrls */
            this.formData.imageUrls = this.formData.imageList.map(item => item.imageUrl)
          } else {
            this.$message.error('数据加载失败，请重试！')
          }
        })
      }
    },
    submitInfo () {
      this.$refs.dataDom.validate(valid => {
        this.formData.size = this.value
        if (valid) {
          this.loading = this.$loading({ text: '加载中...' })
          this.$http.post('/cabinet/update', this.formData).then(data => {
            this.loading.close()
            if (data.code === 0) {
              this.$message({
                message: `${!this.formData.cabinetId ? '添加' : '修改'}成功`,
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('onCloseWin')
                }
              })
            } else {
              this.$alert('操作失败', { type: 'error' })
            }
          })
        }
      })
    },
    beforeUpload (file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      if (!isImg) {
        this.$message.error('文件格式不正确！')
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('文件大小不能超过5M')
      }
      return isImg && isLt5M
    },
    onExceed () {
      this.$message.error('请先删除已存在的图片')
    },
    onSuccess (res) {
      if (res.code === 0) {
        this.formData.cover = res.data
        if (this.fileList.length > 0) {
          this.fileList.length = 0
        }
        this.fileList.push({ url: this.baseImageUrl + res.data })
      } else {
        this.$message.error(res.msg)
      }
    },
    uploadSuccess (res) {
      if (res.code === 0) {
        this.formData.imageUrls.push(res.data) /* 用于上传 */
        this.imageList = this.formData.imageUrls.map(item => { /* 用于显示 */
          return {
            url: this.baseImageUrl + item,
            name: item
          }
        })
      }
    },
    handlePictureCardPreview (file) {
      this.dialogVisible = true
      this.dialogImgSrc = file.url
    },
    showImageDetail (file) {
      this.imageListDialogVisible = true
      this.imageListDialogImgSrc = file.url
    },
    handleRemove (file) {
      this.$confirm('确定删除该图片吗？').then(() => {
        this.formData.cover = ''
        this.$refs.uploadImage.handleRemove(file)
      })
    },
    removeImage (file) {
      this.$confirm('确定删除该图片吗？').then(() => {
        this.$refs.imageListRef.handleRemove(file)
        for (let i = 0; i < this.formData.imageUrls.length; i++) {
          if (this.formData.imageUrls[i] === file.name) {
            this.formData.imageUrls.splice(i, 1)
          }
        }
      })
    }
  },
  created () {
    this.uploadHeader.token = this.$cookies.get('token')
  }
}
</script>

<style scoped>

</style>
